package com.testmock;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.RandomStringUtils;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.xpath.DefaultXPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class DataHelper {
    private static final Logger logger = LoggerFactory.getLogger(DataHelper.class);

    /**
     *
     * @return 21位的时间戳+随机数字字符串的随机字符文本
     */
    public static String generateRand21(){
        StringBuffer sbf = new StringBuffer();
        sbf.append(String.valueOf(System.currentTimeMillis()));
        sbf.append(RandomStringUtils.randomNumeric(8));
        System.out.println("sbf:" + sbf.toString());
        return sbf.toString();
    }

    /**
     *
     * @param srcStr 源带命名空间的XML文本
     * @param xpath  xml文本中需要获取信息的xpath路径
     * @return  获取的文本信息
     * @throws Exception
     */
    public static String paraXml(String srcStr, String xpath) throws Exception {
        Document doc;

        StringBuilder pathBuilder = new StringBuilder();
        Map<String,String> hsMap = new HashMap<String,String>();
        try {
            //logger.debug("需要解析的XML报文：" + srcStr);

            String repStr = handleXML(srcStr);
            logger.debug("处理替换不可见字符后的XML报文：" + repStr);
            //确认命名空间hsmap
            doc = DocumentHelper.parseText(repStr);

            logger.debug("xpath:" + pathBuilder.toString());
            // Xpath 指定路径
            DefaultXPath dxpath = new DefaultXPath(xpath);
            // 指定命名空间
            dxpath.setNamespaceURIs(Collections.singletonMap("ns2", "http://schemas.xmlsoap.org/soap/envelope/"));
            Element ele = (Element)dxpath.selectSingleNode(doc);
            String eleTxt = ele.getText();

            return eleTxt;
        } catch (DocumentException e) {
            e.printStackTrace();
            logger.error("xml解析错误：" + e.getMessage());
            logger.error("报文内容----------->\n" + srcStr);
        }

        return null;
    }

    /**
     *
     * @param srcStr
     * @return去除的不可见字符
     */
    private static String handleXML(String srcStr) {
        String repStr =  srcStr.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");

        if(null != repStr && !"".equals(repStr)){
            logger.debug("repStr:::::::" + repStr);
            logger.debug("lastindexof >,  index <" + String.valueOf(repStr.lastIndexOf(">"))+ String.valueOf(repStr.indexOf("<")));
            if(repStr.indexOf("<") != -1 && repStr.lastIndexOf(">") != -1 &&( repStr.lastIndexOf(">") > repStr.indexOf("<")))
                repStr = repStr.substring(repStr.indexOf("<"), repStr.lastIndexOf(">") + 1);
        }
        return repStr;
    }
}
